package com.zhentao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.zhentao.enty.QrCodeResponse;
import com.zhentao.pojo.User;
import com.zhentao.pojo.UserQrCode;
import com.zhentao.mapper.UserMapper;
import com.zhentao.mapper.UserQrCodeMapper;
import com.zhentao.service.QrCodeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

/**
 * 二维码服务实现类
 */
@Slf4j
@Service
public class QrCodeServiceImpl implements QrCodeService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private UserQrCodeMapper userQrCodeMapper;

    @Value("${qrcode.width:300}")
    private int qrCodeWidth;

    @Value("${qrcode.height:300}")
    private int qrCodeHeight;

    @Value("${qrcode.format:PNG}")
    private String qrCodeFormat;

    @Value("${qrcode.base-url}")
    private String baseUrl;

    @Value("${file.upload.path}")
    private String uploadPath;

    @Value("${file.upload.url-prefix}")
    private String urlPrefix;

    @Override
    public QrCodeResponse generateQrCode(String userId) {
        // 检查用户是否存在
        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }

        // 检查是否已有二维码
        QueryWrapper<UserQrCode> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        UserQrCode existingQrCode = userQrCodeMapper.selectOne(queryWrapper);

        if (existingQrCode != null) {
            // 返回已存在的二维码
            return buildQrCodeResponse(existingQrCode);
        }

        // 生成邀请码
        String inviteCode = generateInviteCode(userId);
        String qrCodeContent = baseUrl + inviteCode;

        try {
            // 生成二维码图片
            String qrCodePath = generateQrCodeImage(qrCodeContent, userId);
            String qrCodeUrl = urlPrefix + userId + ".png";

            // 保存到数据库
            UserQrCode userQrCode = new UserQrCode();
            userQrCode.setUserId(userId);
            userQrCode.setQrCodeContent(qrCodeContent);
            userQrCode.setQrCodeUrl(qrCodeUrl);
            userQrCode.setQrCodePath(qrCodePath);
            userQrCode.setStatus(1);

            userQrCodeMapper.insert(userQrCode);

            return buildQrCodeResponse(userQrCode);
        } catch (Exception e) {
            log.error("生成二维码失败", e);
            throw new RuntimeException("生成二维码失败");
        }
    }

    @Override
    public String getUserIdByInviteCode(String inviteCode) {
        if (!StringUtils.hasText(inviteCode)) {
            return null;
        }

        // 简单的邀请码解码（实际项目中应该使用更复杂的编码方式）
        return inviteCode;
    }

    @Override
    public String generateInviteCode(String userId) {
        // 简单的邀请码生成（实际项目中应该使用更复杂的编码方式）
        return userId;
    }

    private QrCodeResponse buildQrCodeResponse(UserQrCode userQrCode) {
        QrCodeResponse response = new QrCodeResponse();
        response.setUserId(userQrCode.getUserId());
        response.setQrCodeUrl(userQrCode.getQrCodeUrl());
        response.setQrCodeContent(userQrCode.getQrCodeContent());
        response.setInviteCode(generateInviteCode(userQrCode.getUserId()));
        return response;
    }

    private String generateQrCodeImage(String content, String userId) throws WriterException, IOException {
        // 创建二维码写入器
        QRCodeWriter qrCodeWriter = new QRCodeWriter();

        // 设置二维码参数
        Map<EncodeHintType, Object> hints = new HashMap<>();
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        hints.put(EncodeHintType.MARGIN, 2);

        // 生成二维码矩阵
        BitMatrix bitMatrix = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, qrCodeWidth, qrCodeHeight, hints);

        // 创建上传目录
        Path uploadDir = Paths.get(uploadPath);
        if (!Files.exists(uploadDir)) {
            Files.createDirectories(uploadDir);
        }

        // 生成文件路径
        String fileName = userId + ".png";
        Path filePath = uploadDir.resolve(fileName);

        // 将二维码矩阵转换为图片文件
        int width = bitMatrix.getWidth();
        int height = bitMatrix.getHeight();

        java.awt.image.BufferedImage image = new java.awt.image.BufferedImage(width, height, java.awt.image.BufferedImage.TYPE_INT_RGB);

        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
            }
        }

        // 保存图片
        javax.imageio.ImageIO.write(image, "PNG", filePath.toFile());

        return filePath.toString();
    }
}
